from django.shortcuts import render
# 导入响应方法
from django.http import HttpResponse, JsonResponse
from django.views import View
import json
from django.conf import settings
from django.shortcuts import redirect, reverse
from Ganyu.models import BookInfo,HeroInfo
from django.db.models import F,Q,Sum,Avg


# Create your views here.
# 视图方法必须有一个接收参数requests，接收请求报文的数据
def login(request):
    # 编写业务
    return HttpResponse('登入成功')


def register(request):
    return HttpResponse('注册成功')


def userinfo(request):
    return HttpResponse('用户信息')


class UserView(View):
    #              定义参数，接收路径中匹配的数据
    def get(self, request, name, mobile, skill, result):
        # 编写业务
        print(name, skill, result)
        print('正则匹配到的手机号：', mobile)
        return HttpResponse((name, mobile, skill, result))


class RequestDate(View):
    def get(self, request):
        # 获取查询字符串数据
        # data = requset.GET.get()
        data_name = request.GET.getlist('name')
        data_age = request.GET.get('age')
        print(data_name, data_age)
        return HttpResponse('ok')

    def post(self, request):
        # 1.表单数据
        # data = request.POST.getlist('name')
        # age = request.POST.getlist('skill')
        # result = request.POST.getlist('result')
        # print(data,age,result)
        # return HttpResponse((data,age,result))

        data = request.body.decode()
        # 将json转化为字典
        data_dict = json.loads(data)
        # 获取的key值不存在会抛出异常
        print(data_dict['username'])
        # 获取的key值不存在会返回None
        print(data_dict.get('password'))
        return HttpResponse(data_dict)


class HeaderView(View):
    def get(self, request):
        # 获取请求头部数据
        data = request.META
        print(data['PATH'])
        return HttpResponse(data)


class ResponseDataView(View):
    def get(self, request):
        response = HttpResponse(content_type='image/jpg')
        # response.status_code = 599
        # response['name'] = 'xuehua'
        file_path = settings.BASE_DIR + '/Ganyu/QQ图片20210408154853.jpg'
        with open(file_path, 'rb')as f:
            response.content = f.read()

        return response

    def post(self, requset):
        data = {'name': '宿命的狐火-雪华'}

        return JsonResponse(data, status=599)


class RedirectView(View):

    def get(self, request):
        return redirect('http://www.by3636.com')


class ReverseView(View):
    def get(self, request):
        data = reverse('a')
        url = reverse('a') + reverse('b')
        return HttpResponse(url)


class BooksView(View):
    def get(self, request):
        """
            获取图书数据
        :param request:
        :return:
        """
        # # 1.获取所有数据
        # books = BookInfo.objects.all()
        # list = []
        # for book in books:
        #     list.append({
        #         'id': book.id,
        #         'btitle': book.btitle,
        #         'bpub_date': book.bpub_date
        #     })
        # # return HttpResponse(list)
        # # 2.获取一个数据
        # id = request.GET.get('id')
        # try:
        #     data = BookInfo.objects.get(id=id)
        # except:
        #     return HttpResponse('数据不存在',status=405)
        # data_dict = {
        #     'id': data.id,
        #     'btitle': data.btitle
        # }
        # return HttpResponse(json.dumps(data_dict))
        # 3.获取多个数据
        # in在范围内
        # datas = BookInfo.objects.filter(id__in=[1,2,4])
        # 为空
        # datas = BookInfo.objects.filter(id__isnull=False)
        # 大于,大于等于,小于,小于等于
        # datas = BookInfo.objects.filter(bread__gte=20)
        # 是否包含 模糊查询
        # datas = BookInfo.objects.filter(btitle__contains='雪')
        # 以开头或结尾
        # datas = BookInfo.objects.filter(btitle__endswith='狐')
        # 日期
        # datas = BookInfo.objects.filter(bpub_date__year__gte=1980)


        #------------------------------------------#
        # F对象  字段间的数据比较 阅读量大于或者小于评论量的数据
        # datas = BookInfo.objects.filter(bread__lt=F('bcomment'))
        # Q对象  多个条件的与&或|非~查询
        # datas = BookInfo.objects.filter(Q(id=3) |Q(id=2))

        #---------------------------------------#
        # 聚合查询 总数Sum 平均数Avg 最大值Max
        # res = BookInfo.objects.aggregate(Sum('bread'))
        # 获取查询的总个数
        # res = datas.count()
        # 排序
        datas = BookInfo.objects.all().order_by('-id')
        # print(res)
        data_list = []
        for book in datas:
            data_list.append({
                'id': book.id,
                'btitle': book.btitle,
                'bpub_date': book.bpub_date
            })
        return HttpResponse(data_list)
    def post(self, request):
        """
            保存数据
        :param request:
        :return:
        """
        # 1、获取保存的数据  json
        json_str = request.body.decode()
        data_dict = json.loads(json_str)
        btitle = data_dict.get('btitle')
        bpub_date = data_dict.get('bpub_date')
        # 2、验证数据
        if btitle is None or bpub_date is None:
            return HttpResponse('缺少数据', status=405)
        if len(btitle) > 20:
            return HttpResponse('图书名称超过20个', status=405)
        # 3、将数据保存到数据库
        res = BookInfo.objects.create(btitle=btitle, bpub_date=bpub_date)
        print(res)
        # 4、返回结果
        return HttpResponse('保存成功')

    def put(self, request):
        """
            更新数据
        :param request:
        :return:
        """
        # 1.获取更新的数据 json
        json_str = request.body.decode()
        data_dict = json.loads(json_str)
        id = data_dict.get('id')
        btitle = data_dict.get('btitle')
        bpub_date = data_dict.get('bpub_date')
        # 2.验证数据
        if btitle is None or bpub_date is None:
            return HttpResponse('缺少必要数据', status=405)
        if len(btitle) > 20:
            return HttpResponse('图书名称过长,请输入20字符以内', status=405)
        # 3.更新数据filter查询数据
        res = BookInfo.objects.filter(id=id).update(btitle=btitle, bpub_date=bpub_date)
        # 4.返回结果

        return HttpResponse('更新成功')

    def delete(self, request):
        """
            删除数据
        :param request:
        :return:
        """
        # 1.获取数据的id值 查询字符串数据
        id = request.GET.get('id')
        # 2.根据id查询数据进行删除
        # BookInfo.objects.filter(id=id).delete()
        res = BookInfo.objects.filter(id=id)[0]
        res.is_delete = 1
        res.save()
        # 3.删除成功
        return HttpResponse('删除成功')


class BookView(View):
    """
        关联查询
    """
    def get(self,request):
        # 主表图书查询副表英雄 一对多
        book = BookInfo.objects.get(id=1)
        # 根据图书对象查询英雄
        heros = book.heroinfo_set.all()
        book_dict = {}
        book_dict['btitle'] = book.btitle
        hero_list = []
        for hero in heros:
            hero_list.append({
                'id':hero.id,
                'hname':hero.hname
            })
        book_dict['heros'] = hero_list
        # return JsonResponse(book_dict)

        # 副表英雄查询主表图书数据 多对一
        hero = HeroInfo.objects.get(id=10)
        # 通过关联外键获取图书对象
        hero.hbook
        hero_dict = {
            'hname':hero.hname,
            'btitle':hero.hbook.btitle
        }

        return JsonResponse(hero_dict)
